// Copyright (c) 1996-2002 John Lyon-Smith. All rights reserved.

#pragma once

#include <wxtl\base.h>

namespace wxtl
{
	class Handle
	{
	public:
		Handle() throw() :
			m_h(INVALID_HANDLE_VALUE)
		{
		}

		Handle(Handle& h) throw() :
			m_h(INVALID_HANDLE_VALUE)
		{
			attach(h.detach());
		}

		Handle(HANDLE h) throw() :
			m_h(h)
		{
		}

		virtual ~Handle() throw()
		{
			close();
		}

		Handle& operator=(Handle& h) throw()
		{
			if (this != &h)
			{
				attach(h.detach());
			}

			return *this;
		}

		HANDLE get() const throw()
		{
			return m_h;
		}

		void attach(HANDLE h) throw()
		{
			close();
			m_h = h;
		}

		HANDLE detach() throw()
		{
			HANDLE h;

			h = m_h;
			m_h = INVALID_HANDLE_VALUE;

			return h;
		}

		void close() throw(_win32_error)
		{
			if (m_h != INVALID_HANDLE_VALUE)
			{
				if (!::CloseHandle(m_h))
					throw _win32_error(GetLastError());

				m_h = INVALID_HANDLE_VALUE;
			}
		}
		
		virtual bool isValid()
		{
			return (m_h != INVALID_HANDLE_VALUE);
		}

	protected:
		HANDLE m_h;
	};
}